package com.mmx.baseservice.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mmx.baseservice.admin.pojo.AdInfo;
import com.mmx.baseservice.admin.service.AdInfoService;
import com.mmx.baseservice.admin.tools.enums.AdInfoStatus;
import com.mmx.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.mmx.baseservice.common.annotation.repeat.PreventRepeat;
import com.mmx.baseservice.common.config.KeyConfig;
import com.mmx.baseservice.common.mybatisplus.structure.CustomQueryWrapper;
import com.mmx.baseservice.common.utils.CommUtil;
import com.mmx.baseservice.common.utils.SignDecodeUtil;
import com.mmx.baseservice.common.utils.encrypt.RSAUtil;
import com.mmx.baseservice.common.utils.page.pojo.PageInfo;
import com.mmx.baseservice.common.utils.page.pojo.PageResult;
import com.mmx.baseservice.common.utils.page.util.PageUtil;
import com.mmx.baseservice.common.utils.returnbody.Code;
import com.mmx.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.mmx.baseservice.common.utils.returnbody.ReturnBody;
import com.mmx.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author mmx generator
 * @since 2021-02-03
 */
@Api(tags = "管理员-账号信息相关接口")
@RestController
@RequestMapping("admin/adInfo")
public class AdInfoController {

    @Resource
    private HttpServletRequest request;
    @Resource
    BCryptPasswordEncoder encoder;
    @Resource
    private AdInfoService adInfoService;
    @Resource
    private UsInfoService usInfoService;


    @ApiOperation("登录验证")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "account", value = "账号", required = true, example = "PtivnlNFS8UOjbkUyQ6G6n49+c9xIT8npUwsEPpzBNFm0Pt/BVeZkrY6JSf8Rx71ks359U+0Q8d7Iob/P6G9TvWgq0c0SroSzOpsJy6+E7C4Yl12VoorHNE6EImdmPrEdxiEv0ac7HruYP4Nk+D9BIxpf2T0UgDQduFrOkNRWBo="),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "password", value = "密码", required = true, example = "DLUsX3SZ0otbA5J+XE4VrG9K3f2SiLWnyHvSYrQ5CFAkJoFg0AbHKbZnJJsOmSyWwezQvQRWpnYldXmfTrsCFLCPM1RbSgB97f4Wsg0W94+URsPGRLCzRjQlZaGze/uy/DT996rgAskjGh2/1Vy8NE1NGcoE7XjWW+W+JjIGckc="),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "verifyCode", value = "图片验证码", required = true, example = "1234"),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "verifySign", value = "图片验证码密钥", required = true, example = "bOENDfoXAhyXyi8wZ/FsfQxWso6hhErukzPz+s3xQq4=")
    })
    @PostMapping("public/authority")
    @ParameterVerify(notNull = {"account", "password", "verifyCode", "verifySign"})
    public String authority(String account, String password, String verifyCode, String verifySign) throws Exception {
//        password = RSAUtil.decryptByPrivateKey(password);
        //验证码验证
        QueryWrapper<AdInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(account != null, AdInfo.ACCOUNT, account);
        JSONObject verifyResult = SignDecodeUtil.codeMatches(verifyCode, verifySign, 1000000);
        if (!verifyResult.getBoolean("isSuccess")) {
            return ReturnBody.error(Code.IMAGE_CODE_ERROR, verifyResult.getString("errorMessage"));
        }
        return adInfoService.authority(account, password);
    }
    @ApiOperation("账号列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "account", value = "账号", required = false),
    })
    @PostMapping("list")
    public String list(PageInfo pageInfo, String account) {
//         执行分页辅助工具
        PageResult<AdInfo> pageResult = new PageUtil<AdInfo>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(account)){
                queryWrapper.eq(AdInfo.ACCOUNT,account);
            }
            adInfoService.page(page,queryWrapper);
        });

        return ReturnBody.success(pageResult);
    }


    @ApiOperation("添加或修改账号信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "管理员id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "account", value = "账号", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "roleId", value = "角色ID（成员类型）", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "jobId", value = "岗位id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "password", value = "密码", required = false),
    })
    @PostMapping("add")
    @PreventRepeat
    public String add(Long id, String account, String password, Integer roleId, Long jobId) throws Exception {
        Integer rId = (Integer) request.getAttribute(AdInfo.ROLE_ID);
        if (rId != 1) {
            return ReturnBody.error("只有超级管理员可以添加或编辑账号");
        }
        // rsa 解密
        QueryWrapper<AdInfo> queryWrapper = new CustomQueryWrapper<AdInfo>().eq(AdInfo.ACCOUNT, account);
        AdInfo adInfo = adInfoService.getOne(queryWrapper);
        if (null != adInfo) {
            return ReturnBody.error("该账号已存在");
        }
        adInfo = new AdInfo().setJobId(jobId).setRoleId(roleId).setAccount(account);
        if (CommUtil.checkNull(password)) {
            password = RSAUtil.decryptByPrivateKey(password);
            adInfo.setPassword(encoder.encode(password + KeyConfig.KEY_PWD));
        }
        if (CommUtil.checkNull(id)) {
            if (!adInfoService.updateInfo(adInfo).equals("ok")) {
                return ReturnBody.error(ResultCodeInfo.ERROR);
            }
            return ReturnBody.success();
        } else {
            return adInfoService.add(adInfo);
        }
    }


    @ApiOperation("删除账号")
    @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "id", value = "账号ID", required = true)
    @PostMapping("delete")
    @ParameterVerify(notNull = "id")
    public String delete(Integer id) {
        return adInfoService.delete(id);
    }


    @ApiOperation("冻结或解冻操作")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "id", value = "账号ID", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "status", value = "账号状态 0正常，-1冻结", required = true)
    })
    @PostMapping("freezeOrThaw")
    @ParameterVerify(notNull = {"id", "status"})
    public String freezeOrThaw(Integer id, Integer status) {
        if (!status.equals(AdInfoStatus.FREEZE.getValue()) && !status.equals(AdInfoStatus.NORMAL.getValue())) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        AdInfo adInfo = new AdInfo()
                .setId(id)
                .setStatus(status);
        if (!adInfoService.updateById(adInfo)) {
            return ReturnBody.error();
        }
        return ReturnBody.success();
    }



    @ApiIgnore
    @PostMapping("public/test")
    public String test() {
        return ReturnBody.success();
    }


}
